<script setup lang="ts">
  import GoodSelectModal from './GoodSelectModal.vue'
  import { computed, ref } from 'vue'
  import { Good } from '../types'
  import uploadPlaceholderImg from '@/assets/image/avatar_upload_default.png'
  import { UploadFile } from 'element-plus'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import { cloneDeep, debounce } from 'lodash-es'
  import { useGetInfoByProductOrPartCode } from '@/services/pages/code/useCode'

  const { codeInfo, getInfoLoading, getInfo } = useGetInfoByProductOrPartCode()

  defineOptions({
    name: 'GoodsReturnFactoryCreate',
  })

  const props = defineProps({
    userId: {
      type: String,
      default: () => '',
    },
  })

  // 添加设备弹窗显示状态
  const addCommodityDrawerVisible = ref(false)

  // 设备列表
  const goods = ref<Array<Good>>([
    {
      snCode: '',
      goodType: '',
      contractNo: '',
      goodBrand: '',
      goodCode: '',
      goodName: '',
      goodSpec: '',
      qty: 0,
      warrantyStart: '',
      goodId: '',
      goodSpecId: '',
      warrantyEnd: '',
      returnFactoryDesc: '',
      returnFactoryPictureList: [],
      isFixed: true,
      type: 1,
      dl: '',
      specialBz: '',
      standard: '',
      voltage: '',
      xlh: '',
    },
  ])

  // 序列号，用于搜索然后添加到设备列表
  const searchSnCodeVal = ref('')

  // 设备选择集合，用于弹窗回显
  const selectedGoodIds = computed(() => {
    return goods.value.map((good) => {
      return {
        goodId: good.goodId,
        goodSpecId: good.goodSpecId,
        snCode: good.snCode,
      }
    })
  })

  // 返厂图片列宽
  const pictureColumnWidth = ref(130)

  /**
   * 获取表格行的类名，用于固定第一行数据
   */
  const getRowClassName = (data: { row: Good; rowIndex: number }) => {
    if (data.rowIndex === 0) {
      return 'fixed-row'
    }
  }

  /**
   * 删除点击事件
   * @param {Number} index - 索引
   */
  const handleDelClick = (index: number) => {
    goods.value.splice(index, 1)
  }

  /**
   * 删除设备事件
   * @param {Array<CodeRegisteredCodeList>} delGoodList - 待删除的设备列表
   */
  const handleDelGood = (delGoodList: Array<CodeRegisteredCodeList>) => {
    delGoodList.forEach((delGood) => {
      const index = goods.value.findIndex(
        (good) =>
          good.goodId === delGood.goodsId &&
          good.snCode === delGood.code &&
          good.goodSpecId === delGood.goodsSpecId,
      )

      if (index >= 0) {
        goods.value.splice(index, 1)
      }
    })
  }

  /**
   * 删除所有的设备，只留下固定行
   */
  const handleDelAllGood = () => {
    goods.value = [
      {
        contractNo: '',
        snCode: '',
        goodType: '',
        goodBrand: '',
        goodCode: '',
        goodName: '',
        goodSpec: '',
        qty: 0,
        warrantyStart: '',
        goodId: '',
        goodSpecId: '',
        warrantyEnd: '',
        returnFactoryDesc: '',
        returnFactoryPictureList: [],
        isFixed: true,
        type: 1,
        dl: '',
        specialBz: '',
        standard: '',
        voltage: '',
        xlh: '',
      },
    ]
  }

  /**
   * 设备选择事件
   * @param {Array<CodeRegisteredCodeList>} selectGoods - 设备选择列表
   */
  const handleSelectGood = (selectGoods: Array<CodeRegisteredCodeList>) => {
    selectGoods.forEach((selectGood) => {
      const goodIds = goods.value.map((good) => good.goodId)
      const goodSpecIds = goods.value.map((good) => good.goodSpecId)
      const snCodes = goods.value.map((good) => good.snCode)
      if (
        !goodIds.includes(selectGood.goodsId) ||
        !goodSpecIds.includes(selectGood.goodsSpecId) ||
        !snCodes.includes(selectGood.code)
      ) {
        goods.value.push({
          contractNo: selectGood.contractNo || '',
          snCode: selectGood.code,
          goodType: selectGood.goodsType,
          goodBrand: selectGood.goodsBrand,
          goodCode: selectGood.goodsCode || '',
          goodName: selectGood.goodsName,
          goodSpec: selectGood.goodsSpecName,
          qty: 1,
          warrantyStart: selectGood.warrantyStartTime,
          goodId: selectGood.goodsId,
          goodSpecId: selectGood.goodsSpecId,
          warrantyEnd: selectGood.warrantyEndTime,
          returnFactoryDesc: '',
          returnFactoryPictureList: [],
          isFixed: false,
          type: selectGood.type,
          dl: '',
          specialBz: '',
          standard: '',
          voltage: '',
          xlh: '',
        })
      }
    })
  }

  /**
   * 文件上传失败错误提示方法
   * 防抖是为了解决多次触发事件时，会出现多个消息框，影响体验
   */
  const fileUploadFailInfoTip = debounce((msg: string) => {
    HMessageBox.error(msg)
  }, 10)

  /**
   * 图片上传事件
   * @param {UploadFile} file - 文件对象
   * @param {Number} index - 行索引
   */
  const hanldeUploadPicture = (file: UploadFile, index: number) => {
    if (!file.raw) {
      return false
    }

    if (!file.raw.type.includes('image')) {
      fileUploadFailInfoTip(infoTip.returnFactory.create.good_picture_type_err)
      return
    }

    if (goods.value[index].returnFactoryPictureList.length >= 8) {
      fileUploadFailInfoTip(infoTip.returnFactory.create.good_picture_count_err)
      return
    }

    if (file.raw.size / 1024 / 1024 > 50) {
      fileUploadFailInfoTip(infoTip.returnFactory.create.good_picture_size_err)
      return
    }

    goods.value[index].returnFactoryPictureList.push({
      file: file,
      url: URL.createObjectURL(file.raw),
    })

    setPictureColumnWidth()
  }

  /**
   * 移除图片
   * @param {Number} rowIndex - 行索引
   * @param {Number} pictureIndex - 图片索引
   */
  const handleRemovePicture = (rowIndex: number, pictureIndex: number) => {
    goods.value[rowIndex].returnFactoryPictureList.splice(pictureIndex, 1)
    setPictureColumnWidth()
  }

  /**
   * 设置图片列宽
   */
  const setPictureColumnWidth = () => {
    let maxPictureLength = Math.max(
      ...goods.value.map((item) => item.returnFactoryPictureList.length),
    )

    // 在图片数量小于8张时要把上传按钮的宽度计算进去
    if (maxPictureLength < 8) {
      maxPictureLength += 1
    }

    // 这是为了解决删剩一张图时，列宽会变得很小，导致标题会换行
    if (maxPictureLength > 0) {
      pictureColumnWidth.value = maxPictureLength * 60 + (maxPictureLength - 1) * 8 + 24
    }

    if (pictureColumnWidth.value < 130) {
      pictureColumnWidth.value = 130
    }
  }

  /**
   * 搜索并添加设备
   */
  const onSearchAndAddGood = async () => {
    if (!searchSnCodeVal.value) {
      return
    }

    await getInfo(searchSnCodeVal.value)
    if (!codeInfo.value) {
      HMessageBox.warning(infoTip.returnFactory.create.code_search_result_empty)
      return
    }

    const isCodeExist = goods.value.some(
      (good) =>
        good.goodId === codeInfo.value.goodsId &&
        good.goodSpecId === codeInfo.value.goodsSpecId &&
        good.snCode === codeInfo.value.code,
    )
    if (isCodeExist) {
      HMessageBox.error(infoTip.returnFactory.create.code_is_exist)
      return
    }

    goods.value.push({
      contractNo: codeInfo.value.contractNo || '',
      snCode: codeInfo.value.code,
      goodType: codeInfo.value.type === 1 ? '成品' : '物料',
      goodBrand: codeInfo.value.goodsBrand,
      goodCode: codeInfo.value.goodsCode,
      goodName: codeInfo.value.goodsName,
      goodSpec: codeInfo.value.goodsSpecName,
      qty: 1,
      type: codeInfo.value.type,
      warrantyStart: codeInfo.value.warrantyStartTime || '',
      goodId: codeInfo.value.goodsId,
      goodSpecId: codeInfo.value.goodsSpecId,
      warrantyEnd: codeInfo.value.warrantyEndTime || '',
      returnFactoryDesc: '',
      returnFactoryPictureList: [],
      isFixed: false,
      dl: codeInfo.value.dl,
      specialBz: codeInfo.value.specialBz,
      standard: codeInfo.value.standard,
      voltage: codeInfo.value.voltage,
      xlh: codeInfo.value.xlh,
    })

    searchSnCodeVal.value = ''
    HMessage.success('添加成功')
  }

  /**
   * 数量输入事件
   * @param {Number} index - 表格行索引
   */
  // const handleInputQry = (index: number) => {
  //   goods.value[index].qty = Number(String(goods.value[index].qty).replace(/[^\d]/g, ''))
  //   if (goods.value[index].qty < 1) {
  //     goods.value[index].qty = 1
  //   }
  // }

  defineExpose({
    getList: () => {
      // 删除出调用固定行数据
      return cloneDeep(goods.value).filter((good) => !good.isFixed)
    },
    setGoods: (goodList: Array<Good>) => {
      goods.value = goodList
    },
  })
</script>

<template>
  <div class="new-return-factory-commodity-list">
    <div class="title">设备列表</div>
    <div class="table-wrapper">
      <div class="table">
        <el-table
          :border="true"
          :data="goods"
          stripe
          max-height="350"
          :row-class-name="getRowClassName"
          scrollbar-always-on
        >
          <!-- 序号 -->
          <el-table-column width="50" fixed="left" :align="'center'" type="index" label="序号" />

          <!-- 合格证 -->
          <el-table-column width="240" prop="snCode" label="合格证" fixed="left">
            <template #default="{ row }">
              <template v-if="row.isFixed">
                <div class="sncode-search">
                  <el-input
                    v-model.trim="searchSnCodeVal"
                    placeholder="请输入合格证"
                    clearable
                    style="width: 120px"
                  />
                  <h-button type="primary" :loading="getInfoLoading" @click="onSearchAndAddGood"
                    >搜索并添加</h-button
                  >
                </div>
              </template>
              <template v-else>{{ row.snCode }}</template>
            </template>
          </el-table-column>

          <!-- 合同号 -->
          <el-table-column label="合同号" show-overflow-tooltip width="140" prop="contractNo">
            <template #default="{ row }">
              {{ row.isFixed ? '' : row.contractNo }}
            </template>
          </el-table-column>

          <!-- 设备类型 -->
          <!-- <el-table-column prop="goodType" show-overflow-tooltip label="设备类型" width="140" /> -->

          <!-- 品牌 -->
          <!-- <el-table-column prop="goodBrand" show-overflow-tooltip label="品牌" width="140" /> -->

          <!-- 产品编码 -->
          <el-table-column prop="goodCode" show-overflow-tooltip label="产品编码" width="140" />

          <!-- 产品名称 -->
          <el-table-column prop="goodName" show-overflow-tooltip label="产品名称" width="160" />

          <!-- 规格型号 -->
          <el-table-column prop="goodSpec" show-overflow-tooltip label="规格型号" width="160" />

          <!-- 数量 -->
          <el-table-column label="数量" width="100">
            <template #default="{ row }">
              <!-- <el-input
                v-if="!row.isFixed"
                v-model="row.qty"
                placeholder="请输入数量"
                maxlength="6"
                @input="handleInputQry($index)"
              ></el-input> -->
              {{ row.qty >= 1 ? row.qty : '' }}
            </template>
          </el-table-column>

          <!-- 质保开始 -->
          <el-table-column prop="warrantyStart" label="质保开始" width="140" />

          <!-- 质保结束 -->
          <el-table-column prop="warrantyEnd" label="质保结束" width="140" />

          <!-- 返厂描述 -->
          <el-table-column prop="returnFactoryDesc" label="返厂描述" width="280">
            <template #default="{ row }">
              <el-input
                v-if="!row.isFixed"
                v-model.trim="row.returnFactoryDesc"
                resize="both"
                type="textarea"
                maxlength="200"
                show-word-limit
                placeholder="请输入返厂描述"
                class="return-factory-desc"
              />
            </template>
          </el-table-column>

          <!-- 返厂图片 -->
          <el-table-column
            prop="returnFactoryPictureList"
            label="返厂图片"
            :width="pictureColumnWidth"
          >
            <template #default="{ row, $index }">
              <div v-if="!row.isFixed" class="picture-wrapper">
                <template v-for="(img, index) in row.returnFactoryPictureList" :key="index">
                  <h-image
                    :preview-src-list="row.returnFactoryPictureList.map((item) => item.url)"
                    :width="60"
                    :height="37.5"
                    fit="scale-down"
                    :src="img.url"
                    :initial-index="index"
                    :padding="2"
                    :mask-btn-gap="3"
                    :show-del-btn="!img.id"
                    @del="handleRemovePicture($index, index)"
                  />
                </template>
                <h-image
                  v-if="row.returnFactoryPictureList.length < 8"
                  :src="uploadPlaceholderImg"
                  :width="60"
                  :height="37.5"
                  :padding="2"
                >
                  <el-upload
                    action="#"
                    multiple
                    accept="image/*"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: UploadFile) => hanldeUploadPicture(file, $index)"
                  >
                    <i class="iconfont icon-img-upload" style="font-size: 24px; color: #fff"></i>
                  </el-upload>
                </h-image>
              </div>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column width="100" fixed="right" label="操作">
            <template #header>
              <h-link @click="addCommodityDrawerVisible = true">选择产品</h-link>
            </template>
            <template #default="{ $index }">
              <h-link type="error" @click="handleDelClick($index)">删除</h-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <good-select-modal
      v-model:visible="addCommodityDrawerVisible"
      :user-id="props.userId"
      :default-select-good="selectedGoodIds"
      @select-good="handleSelectGood"
      @del-good="handleDelGood"
      @del-all-good="handleDelAllGood"
    />
  </div>
</template>

<style scoped lang="scss">
  .picture-wrapper {
    display: flex;
    gap: 8px;
    height: 40px;
  }

  .sncode-search {
    display: flex;
    column-gap: 5px;
  }

  :deep(.el-table__body-wrapper) {
    .el-scrollbar {
      .el-scrollbar__wrap {
        box-sizing: border-box;
        padding-bottom: 13px;
      }
    }
  }

  .return-factory-desc {
    :deep(.el-textarea__inner) {
      height: 28px;
      min-height: 28px !important;
      max-height: 220px !important;
      width: 250px !important;
    }
  }

  :deep(.fixed-row) {
    position: sticky;
    position: -webkit-sticky;
    top: 0;
    z-index: 3;
  }

  .new-return-factory-commodity-list {
    display: flex;
    flex-direction: column;
    row-gap: 8px;
    height: 100%;

    .title {
      font-size: 14px;
      font-weight: bold;
      padding-left: 6px;
      border-left: 3px solid $primaryColor;
    }

    .table-wrapper {
      flex: 1;
    }
  }
</style>
